package cn.tom.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.tom.entity.*;

import cn.tom.service.*;

import cn.tom.tool.Token;
import cn.tom.tool.XJson;
import cn.tom.tool.XResp;
import java.io.IOException;
import java.time.Duration;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RequestMapping({"/api/public"})
@RestController
public class PublicController {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    BookTypeService bookTypeService;
    @Autowired
    LargeFileService largeFileService;
    @Autowired
    BookService bookService;
    @Autowired
    UserService userService;

    @Autowired
    CommentService commentService;

    @Autowired
    HotService hotService;

    @Autowired
    CartService cartService;

    @Autowired
    MailService mailService;

    @Autowired
    PasswordEncoder passwordEncoder;






    @GetMapping("/checkToken")
    public XJson checkToken( ) {
        log.info("checkToken");
        int uid = -1;
        uid = Token.getUid();
        if (uid < 0) {
            return XResp.pack(401, "token失效", null);
        }
        return XResp.pack(200, "token有效", null);
    }

    @GetMapping("/sendCaptcha/{emailName}")
    public XJson sendCaptcha(@PathVariable("emailName") String emailName) {
        mailService.setCaptcha(emailName);
        String captcha = mailService.getCaptcha(emailName);
        if (captcha!=null) {
            return XResp.pack(200,"发送验证码成功","");
        }
        return XResp.pack(201,"发送验证码失败","");
    }

    @GetMapping("/book/findRecord/{bookid}")
    public XJson findRecord(@PathVariable("bookid") Integer bookid) {
        int uid = Token.getUid();
        if (uid < 0) {
            return XResp.pack(201, "未登录无法评价", null);
        }
        int ret = this.bookService.findRecord(uid, bookid);
        if (ret >0) {
            return XResp.pack(200,"购买过该商品可以评价","");
        }
        return XResp.pack(202,"未购买过该商品","");
    }

    @GetMapping({"/type/findAll2"})
    public XJson getBookTypes2() {
        return XResp.pack(200, "", this.bookTypeService.findAll2());
    }

    @GetMapping({"/showimg/{id}"})
    public void dispaly(@PathVariable("id") String id, HttpServletResponse response) {
        byte[] buf;
        if (id != null) {
            try {
                buf = (byte[]) this.largeFileService.findOne(id).getContent();
            } catch (NullPointerException e) {
                buf = new byte[1];
            }
            try {
                response.setContentType("image/jpeg");
                response.getOutputStream().write(buf);
                response.flushBuffer();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
    @GetMapping({"/addCart/{bookid}"})
    public XJson addCart(@PathVariable("bookid") int bookid) {
        this.log.info("addcart bookid=" + bookid);
        int uid = Token.getUid();
        this.log.info("uid======" + uid);
        if (uid < 0) {
            return XResp.pack(401, "请登录之后再进行此操作", 0);
        }
        Book book = this.bookService.findById(bookid);
        Cart cart = new Cart();
        cart.setBook(book);
        cart.setUid(uid);
        Integer num=1;
        Cart idNum = this.cartService.findNumByUidAndBid(uid,bookid);

        log.info("====================findNumByUidAndBid(uid,bookid)="+ idNum);
        if (idNum!=null && idNum.getNum()>=1) {
            cart.setId(idNum.getId());
            cart.setNum(idNum.getNum()+1);
            num = cart.getNum();
        }

        cart.setNum(num);
        cart.setPrice(book.getPrice());
        if (num>1) {

            log.info("修改数量=========");
            Integer ret2 = this.cartService.updateNum(cart);
            return XResp.pack(200,"已在购物车，已增加购买数量",null);
        }
        this.cartService.add(cart);
        return XResp.pack(200, "加入购物车成功 ...", null);
    }


    @PostMapping({"/addUser"})
    public XJson addUser(@RequestParam(value = "mypic", required = false) MultipartFile file, Usr u) throws IOException {
        this.log.info("file=" + file);
        this.log.info("================添加用户=" + u);
        if (this.userService.findByAccount(u.getAccount()) != null) {
            return XResp.pack(200, "注册失败， 账号重复", null);
        }
        if (file != null && file.getSize() > 0) {
            if (u.getImg() != null) {
                this.largeFileService.delete(u.getImg());
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");
            u.setImg(uuid);
            this.largeFileService.add(uuid, file.getOriginalFilename(), file.getBytes());
        }
        u.setRole("usr");
        this.userService.add(u);
        u.setPassword("");
        return XResp.pack(200, "注册成功 ...", u);
    }

    @GetMapping({"/findHot/{type}/{num}"})
    public XJson findHot(@PathVariable("type") int type, @PathVariable("num") int num) {
        return XResp.pack(200, "", this.hotService.findByType(type, num));
    }


    @GetMapping({"/findPageBook/{start}/{num}/{typeid}"})
    public XJson findPages_book(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid) {
        this.log.info("==========/findPageBook/{start}/{num}/{typeid}   start=" + start + "  num=" + num + "  typeid=" + typeid);
        Map<String, Object> map = new HashMap<>();
        Integer start2 = (start - 1) * num;
        map.put("books", this.bookService.findPageType(start2,num,typeid));
        map.put("total", this.bookService.getCountType(typeid));
        return XResp.pack(200, "", map);
    }

    @PostMapping({"/book/findPageKey/{start}/{num}"})
    public XJson findBookPageByKey(@PathVariable("start") Integer start, @PathVariable("num") Integer num, String str) {
        List<Book> list = new ArrayList<>();
        Integer start2 = (start - 1) * num;
        System.out.println("/book/findPageKey/{start}/{num} start=" + start2 + "  num=" + num + "  str=" + str);
        if (str == null || str.length() < 2) {
            return XResp.pack(100, "搜索关键字不能短于2 ", list);
        }
        List<Book> like = this.bookService.findLike(str, start2, num);
        int total = this.bookService.findLikeNum(str);
        Map<String, Object> map = new HashMap<>();
        map.put("books", like);
        map.put("total", total);
        return XResp.pack(200, "", map);
    }


    @GetMapping({"/book/findById/{bookid}"})
    public XJson findById(@PathVariable Integer bookid) {
        return XResp.pack(200, "", this.bookService.findById(bookid));
    }

    @GetMapping({"/book/findTopSale/{num}"})
    public XJson findTopSale(@PathVariable("num") Integer num) {
        return XResp.pack(200, "", this.bookService.findTopSale(num));
    }

    @PostMapping({"/rate/add/{bookid}"})
    public XJson add(@PathVariable("bookid") Integer bookid, String content, Integer rate) {
        this.log.debug("添加评论：bookid=" + bookid + "====rate=" + rate + "===content=" + content);
        Usr user = Token.getUser();
        log.info("======评论usr======" + user);
        if (user == null) {
            return XResp.pack(100, "未登录", null);
        }
        Comment c = new Comment();
        c.setBookid(bookid);
        c.setContent(content);
        c.setImg(user.getImg());
        c.setNickname(user.getNickname());
        c.setUid(user.getId());
        c.setTpost(new Date());
        c.setRate(rate);
        int ret = this.commentService.add(c);
        if (ret==1) {
            return XResp.pack(200, "评论成功", null);
        }
        return XResp.pack(201, "评论失败", null);
    }

    @GetMapping({"/rate/findByBookid/{bookid}/{start}/{num}"})
    public XJson findByBookid(@PathVariable("bookid") Integer bookid, @PathVariable("start") Integer start, @PathVariable("num") Integer num) {
        this.log.info("=======/rate/findByBookid/ bookid=" + bookid + "start=" + start + "num=" + num);
        if (start == null) {
            start = 1;
        }
        if (num == null) {
            num = 5;
        }
        if (bookid == null) {
            return XResp.pack(100, "没有书本id", null);
        }
        Object lst = this.commentService.findByBookid(bookid, (start - 1) * num, num);
        this.log.info(lst.toString());
        int total = this.commentService.getCountByBookid(bookid);
        Map<String, Object> map = new HashMap<>();
        map.put("comments", lst);
        map.put("total", total);
        this.log.info(lst.toString());
        return XResp.pack(200, "", map);
    }

    @GetMapping("/book/findAll2")
    public XJson BookfindAll() {
        List<Book> list = bookService.findAll2();
        return XResp.pack(200, "", list);
    }
}
